<template>
  <div class="page-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h3>个人资料</h3>
          <el-button type="primary" @click="handleEdit" v-if="!isEditing">
            <el-icon><Edit /></el-icon>
            编辑资料
          </el-button>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="!isEditing"
      >
        <div class="avatar-section">
          <el-avatar :size="80" :src="form.avatar">
            {{ form.realName ? form.realName.charAt(0) : 'U' }}
          </el-avatar>
          <div class="avatar-info">
            <h4>{{ form.realName || '未设置姓名' }}</h4>
            <p>{{ form.username }}</p>
          </div>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入头像URL" />
        </el-form-item>
        
        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存修改
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 修改密码卡片 -->
    <el-card class="password-card">
      <template #header>
        <h3>修改密码</h3>
      </template>
      
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 账号管理卡片 -->
    <el-card class="account-card">
      <template #header>
        <h3>账号管理</h3>
      </template>
      
      <div class="account-actions">
        <div class="action-item">
          <div class="action-info">
            <h4>注销账号</h4>
            <p class="action-desc">注销后账号将无法恢复，请谨慎操作</p>
          </div>
          <el-button type="danger" @click="showDeleteConfirm" :loading="deleting">
            注销账号
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 注销账号确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认注销账号"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="delete-warning">
        <el-icon class="warning-icon" color="#f56c6c"><WarningFilled /></el-icon>
        <p>注销账号后，以下数据将被永久删除：</p>
        <ul>
          <li>个人资料和头像</li>
          <li>收货地址信息</li>
          <li>历史订单记录</li>
          <li>购物车数据</li>
        </ul>
        <p class="confirm-text">请输入您的密码以确认注销：</p>
        <el-input
          v-model="deletePassword"
          type="password"
          placeholder="请输入密码"
          show-password
          @keyup.enter="handleDeleteAccount"
        />
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteAccount" :loading="deleting">
            确认注销
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, WarningFilled } from '@element-plus/icons-vue'
import { getUserInfo, updateUserInfo, changePassword, deleteAccount } from '../../api/user'

const router = useRouter()
const userStore = useUserStore()

const formRef = ref()
const passwordFormRef = ref()
const isEditing = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const deleting = ref(false)
const deleteDialogVisible = ref(false)
const deletePassword = ref('')

const form = reactive({
  username: '',
  realName: '',
  phone: '',
  email: '',
  avatar: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await getUserInfo()
    const userInfo = response.data
    Object.assign(form, userInfo)
    // 更新全局用户信息
    userStore.setUserInfo(userInfo)
  } catch (error) {
    console.error('加载用户信息失败:', error)
    // 如果存在缓存的用户信息，则使用缓存
    if (userStore.userInfo) {
      Object.assign(form, userStore.userInfo)
    }
  }
}

const handleEdit = () => {
  isEditing.value = true
}

const handleCancel = () => {
  isEditing.value = false
  loadUserInfo() // 重新加载原始数据
}

const handleSave = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  saving.value = true
  try {
    await updateUserInfo(form)
    ElMessage.success('个人信息更新成功')
    isEditing.value = false
    // 更新全局用户信息
    userStore.setUserInfo(form)
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败')
  } finally {
    saving.value = false
  }
}

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  const valid = await passwordFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  changingPassword.value = true
  try {
    await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    ElMessage.success('密码修改成功，请重新登录')
    
    // 清空密码表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
    
    // 延迟一下后退出登录
    setTimeout(() => {
      userStore.logout()
      router.push('/login')
    }, 1500)
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请检查当前密码是否正确')
  } finally {
    changingPassword.value = false
  }
}

const showDeleteConfirm = () => {
  deletePassword.value = ''
  deleteDialogVisible.value = true
}

const handleDeleteAccount = async () => {
  if (!deletePassword.value) {
    ElMessage.error('请输入密码')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '此操作不可逆，确定要注销账号吗？',
      '最后确认',
      {
        confirmButtonText: '确定注销',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
  } catch {
    return
  }
  
  deleting.value = true
  try {
    await deleteAccount({ password: deletePassword.value })
    ElMessage.success('账号注销成功')
    deleteDialogVisible.value = false
    
    // 清理用户数据并跳转登录
    setTimeout(() => {
      userStore.logout()
      router.push('/login')
    }, 1000)
  } catch (error) {
    console.error('注销账号失败:', error)
    ElMessage.error('注销账号失败，请检查密码是否正确')
  } finally {
    deleting.value = false
  }
}

// 页面初始化时加载用户信息
onMounted(() => {
  loadUserInfo()
})

</script>

<style scoped>
.page-container {
  padding: 0;
  background: #f0f2f5;
  min-height: calc(100vh - 60px);
  width: 100%;
  margin: 0;
  box-sizing: border-box;
}

.profile-card {
  margin: 24px;
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.avatar-info {
  margin-left: 20px;
}

.avatar-info h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.avatar-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.password-card {
  margin: 24px;
  margin-bottom: 24px;
}

.password-card :deep(.el-card__header) {
  padding: 16px 20px;
}

.password-card h3 {
  margin: 0;
  color: #303133;
}

.account-card {
  margin: 24px;
}

.account-actions {
  padding: 20px 0;
}

.action-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background: #fafafa;
}

.action-info h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.action-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.delete-warning {
  text-align: center;
}

.warning-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.delete-warning p {
  margin: 16px 0;
  color: #666;
}

.delete-warning ul {
  text-align: left;
  margin: 16px 0;
  padding-left: 20px;
}

.delete-warning li {
  margin: 8px 0;
  color: #666;
}

.confirm-text {
  font-weight: bold;
  color: #f56c6c !important;
  margin-top: 20px !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
  }
  
  .avatar-info {
    margin-left: 0;
    margin-top: 16px;
  }
  
  .action-item {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
}
</style>
